// tfgets.c
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <string.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

static sigjmp_buf env;

void handler(int signal)
{
    alarm(0);
    longjmp(env, 1);
}

char *tfgets(char *buffer, int buffer_size, FILE *stream)
{

    signal(SIGALRM, handler);

    alarm(5);
    if (!sigsetjmp(env, 1))
        return fgets(buffer, buffer_size, stream);
    else
        return NULL;
}

int main()
{
    char *str;
    char buffer[100];

    while (1)
    {
        if (tfgets(buffer, sizeof(buffer),stdin) != NULL)
            printf("read: %s", buffer);
        else
            printf("time out\n");
    }

    exit(0);
}